package com.xbongbong.pro.statistic.help;

import com.alibaba.fastjson.JSONArray;
import com.xbongbong.paas.elasticsearch.util.EsHelper;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.pro.statistic.enums.ChartTypeEnum;
import com.xbongbong.pro.statistic.result.pojo.FieldAttrPojo;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

/**
 * 钻取相关公共方法抽取
 *
 * @author xbongbong
 * @version v1.0
 * 创建时间 2022/9/30 17:05
 * @since v1.0
 */
@Component
public class DrillHelp {

    /**
     * 钻取的匹配规则
     *
     * @param drillFieldAttrPojo 钻取的层级属性
     * @param fieldAttrPojo      行列分组
     * @return true 当前钻取字段就是当前行列分组
     */
    public boolean drillMatchRule(FieldAttrPojo drillFieldAttrPojo, FieldAttrPojo fieldAttrPojo) {
        if (Objects.isNull(drillFieldAttrPojo) || Objects.isNull(fieldAttrPojo)) {
            return false;
        }
        String drillOriginalAttr = drillFieldAttrPojo.getOriginalAttr();
        String originalAttr = fieldAttrPojo.getOriginalAttr();
        // 钻取字段的attr
        String drillAttr = Objects.isNull(drillOriginalAttr) ? drillFieldAttrPojo.getAttr() : drillOriginalAttr;
        // 图表设计字段的attr
        String attr = Objects.isNull(originalAttr) ? fieldAttrPojo.getAttr() : originalAttr;
        if (Objects.equals(drillFieldAttrPojo.getType(), fieldAttrPojo.getType())
                && Objects.equals(drillFieldAttrPojo.getFormId(), fieldAttrPojo.getFormId())
                && Objects.equals(drillAttr, attr)) {
            if (EsHelper.isDateTimeByFieldType(fieldAttrPojo.getFieldType())) {
                return Objects.equals(drillFieldAttrPojo.getDateGroupType(), fieldAttrPojo.getDateGroupType());
            } else {
                return true;
            }
        }
        return false;
    }

    /**
     * 得到统计图下钻、上卷目标字段在钻取层级的索引
     * @param goalDrillField 钻取目标字段（下钻、上卷后的指向字段）
     * @param currentDrillAttrList 该层级的字段attrList
     * @param field 层级内各个层级字段信息
     * @return int
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    public int getDrillIndex(FieldAttrPojo goalDrillField, List<String> currentDrillAttrList, List<FieldAttrPojo> field){
        int drillIndex = 0;
        //只有时间字段在钻取层级内attr可能是一致的，还需要结合dateGroupType
        if (EsHelper.isDateTimeByFieldType(goalDrillField.getFieldType())) {
            for (int i = 0; i < field.size(); i++) {
                if (drillMatchRule(field.get(i), goalDrillField)) {
                    drillIndex = i;
                    break;
                }
            }
        } else {
            //直接从 当前钻取字段所属层级内所有的字段attrList 内得到字段
            drillIndex = currentDrillAttrList.indexOf(goalDrillField.getAttr());
        }
        if (drillIndex < 0) {
            drillIndex = 0;
        }
        return drillIndex;
    }

}
